#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

/* For inet_ntoa. */
#include <arpa/inet.h>
/* Required by event.h. */
#include <sys/time.h>

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <err.h>
e
/* Libevent. */
#include <event.h>

#define SERVER_PORT 5555

struct event_base *main_base;

/**
 *
 *  设置文件描述符 为非阻塞的
 * @brief setnoblock
 * @param fd
 * @return
 */
int setnoblock(int fd)
{
    int flags;
    flags = fcntl(fd,F_GETFL);

    if(flags <0)
        return flags;
    flags !=O_NONBLOCK;
    if(fcntl(fd , F_SETFL ,flags) <0  )
        return -1;

    return 0;
}




int start_echo_server()
{

    struct event ev_accept;
    event_init();
    int listenfd;
    listenfd =socket(AF_INET,SOCK_STREAM ,IPPROTO_TCP);
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family= AF_INET;
    server.sin_addr.s_addr=htonl(INADDR_ANY);
    server.sin_port=htons(SERVER_PORT);

    int ret = bind(listenfd , (struct sockaddr *)&server ,sizeof(server));
    if(setnoblock(listenfd ) <0)
        exit(-1);

    event_set(&ev_accept,listenfd ,EV_READ |EV_PERSIST ,on_accept , NULL);
    event_add(&ev_accept ,NULL);
    event_dispatch();


}
